import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    Dimensions,
    ListView,
    TouchableOpacity,
    TextInput,
    DeviceEventEmitter,
    AsyncStorage,
    Platform,
    StatusBar
} from 'react-native';
import Config from '../../common/Config'
import Utils from '../../common/Utils'
import {Toast,ModalIndicator} from 'teaset';
const STORAGE_KEY_TOKEN = '@AsyncStorageDemo:key_token';
const {height, width} = Dimensions.get('window');
export default class ModifyNotesPage extends Component {
    componentDidMount() {
        this.msgListener = DeviceEventEmitter.addListener('refreshed',(listenerMsg) => {
            this.getInfo();
        });
        this._loadInitialState().done();
    }
    async _loadInitialState(){
        try{
            let value=await AsyncStorage.getItem(STORAGE_KEY_TOKEN);
            if(value!==null){
                this._appendMessage(value);
            }else{
                this._appendMessage('');
            }
        }catch(error){
            this._appendMessage('AsyncStorage错误'+error.message);
        }
    }
    _appendMessage=(message)=>{
        this.setState({
            token:this.state.token.concat(message)
        },()=>this.getInfo());
    };
    getInfo=()=>{
        let params={
            "token":this.state.token,
            "coverId":this.props.id
        };
        fetch(Config.baseApi+'/directories/getInfo',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: Utils.getParamsString(params)
        })
            .then((response) => response.json())
            .then((responseJson) => {
                if(responseJson.status===0){
                    if(responseJson.data.remarkVO===null){
                        this.setState({
                            name:'',
                            label:'',
                            phone:''
                        })
                    }else {
                        if(responseJson.data.remarkVO.name!==null){
                            this.setState({
                                name:responseJson.data.remarkVO.name
                            })
                        }else {
                            this.setState({
                                name:''
                            })
                        }
                        if(responseJson.data.remarkVO.label!==null){
                            this.setState({
                                label:responseJson.data.remarkVO.label
                            })
                        }else {
                            this.setState({
                                label:''
                            })
                        }
                        if(responseJson.data.remarkVO.phone!==null&&responseJson.data.remarkVO.phone!=''){
                            this.setState({
                                phone:responseJson.data.remarkVO.phone
                            })
                        }else {
                            this.setState({
                                phone:''
                            })
                        }
                    }
                }else{
                    Toast.message(responseJson.msg);
                }
            })
            .catch((error) => {
                Toast.message(error);
            });
    };
    constructor(props) {
        super(props);
        this.state = {
            phone:''||this.props.phone,
            nickname:''||this.props.nickname,
            label:'',
            token:'',
            isPhone:true
        }
    };

    isPhoneTrue=()=>{
        let regex = /^1(3|4|5|7|8)\d{9}$/;
        let checkPhone=regex.test(this.state.phone);
        if(this.state.phone!=''){
            this.setState({
                isPhone:false
            },()=>{
                if(checkPhone==true){
                    this.setState({
                        isPhone:true
                    })
                }
            });
        }
    };

    complete=()=>{
        this.phoneTextInput.blur();
        this.nameTextInput.blur();
        if(this.state.phone!=''){
            if(this.state.phone.length!=11){
                Toast.message('手机号长度不正确')
            }else if(this.state.isPhone!=true){
                Toast.message('请输入正确的手机号')
            }else {
                let params={
                    "token":this.state.token,
                    "coverId":this.props.id,
                    "label":this.state.label,
                    "phone":this.state.phone,
                    "name":this.state.nickname
                };
                ModalIndicator.show("正在请求数据......");
                fetch(Config.baseApi+'/directories/updateRemark',{
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: Utils.getParamsString(params)
                })
                    .then((response) => response.json())
                    .then((responseJson) => {
                        ModalIndicator.hide();
                        if(responseJson.status!==1){
                            Actions.pop();
                            DeviceEventEmitter.emit('refreshHome','aaa')
                        }else{
                            Toast.message(responseJson.msg);
                        }
                    })
                    .catch((error) => {
                        ModalIndicator.hide();
                        Toast.message(error);
                    });
            }
        }else {
            let params={
                "token":this.state.token,
                "coverId":this.props.id,
                "label":this.state.label,
                "phone":this.state.phone,
                "name":this.state.nickname
            };
            ModalIndicator.show("正在请求数据......");
            fetch(Config.baseApi+'/directories/updateRemark',{
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: Utils.getParamsString(params)
            })
                .then((response) => response.json())
                .then((responseJson) => {
                    ModalIndicator.hide();
                    if(responseJson.status!==1){
                        Actions.pop();
                        DeviceEventEmitter.emit('refreshHome','aaa')
                    }else{
                        Toast.message(responseJson.msg);
                    }
                })
                .catch((error) => {
                    ModalIndicator.hide();
                    Toast.message(error);
                });
        }
    };

    render() {
        return (
            <View style={styles.container}>
                <StatusBar
                    backgroundColor="black"
                    barStyle="light-content"
                />
                <View style={styles.titleView}>
                    <TouchableOpacity
                        onPress={()=>Actions.pop()&&DeviceEventEmitter.emit('refreshHome','aaa')}
                        style={styles.goBackView}>
                        <Image
                            source={ImageUtil.WhiteGoBack}
                            style={styles.goBackImg}/>
                    </TouchableOpacity>
                    <Text style={styles.titleMsg}>修改标签及备注</Text>
                    <TouchableOpacity
                        onPress={()=>this.complete()}
                        style={styles.completeView}>
                        <Text style={[styles.titleMsg,{marginBottom:Platform.OS==='ios'?29/2:10}]}>完成</Text>
                    </TouchableOpacity>
                </View>
                <View style={{height:26,width:width,justifyContent:'center'}}>
                    <Text style={{marginLeft:15,fontSize:14,color:'#646464'}}>备注名</Text>
                </View>
                <View style={styles.areaView}>
                    <TextInput
                        ref={ (ref)=>this.nameTextInput = ref }
                        autoCapitalize={"none"}
                        underlineColorAndroid={'transparent'}
                        defaultValue={this.state.nickname}
                        style={{flex:1,paddingLeft:15,fontSize:14}}
                        placeholder="添加备注名"
                        placeholderTextColor='#b2b2b2'
                        autoCorrect={false}
                        onChangeText={(text)=>{
                            this.setState({
                                nickname:text,
                            });
                        }}/>
                </View>
                <View style={{height:26,width:width,justifyContent:'center'}}>
                    <Text style={{marginLeft:15,fontSize:14,color:'#646464'}}>标签</Text>
                </View>
                {this.state.label!==null&&this.state.label!=''
                ?(<TouchableOpacity
                        onPress={()=>Actions.SetLabelPage({id:this.props.id,nickname:this.state.nickname,phone:this.state.phone})}
                        style={styles.areaView}>
                        <Text style={{marginLeft:15, fontSize:14,color:'#3090dd'}}>
                            {this.state.label}
                        </Text>
                        <Image
                            source={ImageUtil.Guide}
                            style={{position: 'absolute',right:15,height:17,width:17}}/>
                    </TouchableOpacity>)
                :(<TouchableOpacity
                        onPress={()=>Actions.SetLabelPage({id:this.props.id,nickname:this.state.nickname,phone:this.state.phone})}
                        style={styles.areaView}>
                        <Text style={{marginLeft:15, fontSize:14,color:'#b2b2b2'}}>通过标签给联系人分类</Text>
                        <Image
                            source={ImageUtil.Guide}
                            style={{position: 'absolute',right:15,height:17,width:17}}/>
                    </TouchableOpacity>)}
                <View style={{height:26,width:width,justifyContent:'center'}}>
                    <Text style={{marginLeft:15,fontSize:14,color:'#646464'}}>电话号码</Text>
                </View>
                <View style={styles.areaView}>
                    <TextInput
                        ref={ (ref)=>this.phoneTextInput = ref }
                        autoCapitalize={"none"}
                        underlineColorAndroid={'transparent'}
                        style={{flex:1,paddingLeft:15,fontSize:14}}
                        keyboardType={"numeric"}
                        placeholder="添加电话号码"
                        defaultValue={this.state.phone}
                        maxLength={11}
                        placeholderTextColor='#b2b2b2'
                        autoCorrect={false}
                        onChangeText={(text)=>{
                            this.setState({
                                phone:text,
                            },()=>this.isPhoneTrue());
                        }}/>
                </View>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor:'#f0f0f0'
    },
    titleView:{
        backgroundColor:'#000000',
        width:width,
        alignItems:'center',
        justifyContent:'center',
        height:Platform.OS==='ios'?64:44
    },
    titleMsg:{
        fontSize:17,
        color:'#ffffff',
        marginTop:Platform.OS==='ios'?34:14,
        marginBottom:29/2
    },
    goBackView:{
        position: 'absolute',
        top:Platform.OS==='ios'?65/2:25/2,left:15,
    },
    goBackImg:{
        height:18,
        width:18
    },
    completeView:{
        position: 'absolute',
        right:15,bottom:0
    },
    areaView:{
        flexDirection:'row',
        height:46,
        borderTopWidth:1,
        borderBottomWidth:1,
        borderColor:'#e3e3e4',
        alignItems:'center',
        backgroundColor:'#ffffff'
    },
});
